﻿using System.Collections;
using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

public class FriendListPanel : BasePanel
{


	public Button chatListBtn;
	public Button friendListBtn;
	public Button myBtn;

	public Button addFriendBtn;

	private GameObject _friendItemPrefab;

	private QueryFriendListRequest _queryFriendListRequest;
	// Use this for initialization
	void Start () {
		//组件初始化
		_friendItemPrefab = Resources.Load<GameObject>("UIPanel/FriendItem");
		_queryFriendListRequest = this.gameObject.GetComponent<QueryFriendListRequest>();
		
		chatListBtn.onClick.AddListener(delegate { ChatListButtonClicked(); });
		friendListBtn.onClick.AddListener(delegate { FriendListButtonClicked(); });
		myBtn.onClick.AddListener(delegate { MyButtonClicked(); });
		addFriendBtn.onClick.AddListener(delegate { AddFriendButtonClicked(); });
	}
	
	// Update is called once per frame
	void Update () {
		
	}


	private void ChatListButtonClicked()
	{	
		UnityFacade.Instance.UiManager.PopPanel();

		UnityFacade.Instance.UiManager.PushPanel(PanelType.ChatListPanel);

	}


	private void FriendListButtonClicked()
	{
		// 执行好友列表请求拉取
		_queryFriendListRequest.SendRequest();
	}


	private void MyButtonClicked()
	{
		UnityFacade.Instance.UiManager.PopPanel();

		UnityFacade.Instance.UiManager.PushPanel(PanelType.MyPanel);
	}


	private void AddFriendButtonClicked()
	{
		UnityFacade.Instance.UiManager.PushPanel(PanelType.SearchFriendPanel);
	}
	
	public override void OnEnter()
	{
		if (!this.gameObject.activeSelf )
		{
			this.gameObject.SetActive(true);
		}

		if (_queryFriendListRequest == null)
		{
			_queryFriendListRequest = this.gameObject.GetComponent<QueryFriendListRequest>();
		}
		//重新拉取一次数据
		_queryFriendListRequest.SendRequest();
	}

	public override void OnPause()
	{
		//todo UI动画
		this.gameObject.SetActive(false);
	}

	public override void OnResume()
	{
		//todo UI动画
		if (!this.gameObject.activeSelf )
		{
			this.gameObject.SetActive(true);
		}
	}

	public override void OnExit()
	{
		this.gameObject.SetActive(false);
	}

	public void HandleResponse(JsonData respJsonData)
	{
		//销毁已有的FriendItem
		GameObject[] friendItemGOS = GameObject.FindGameObjectsWithTag("FriendItem");
		foreach (GameObject go in friendItemGOS)
		{
			Destroy(go);
		}
		
		//查找挂载点V_Layout
		Transform v_Layout_pos = UnityFacade.Instance.UiManager.InstantiatedPanelDict[PanelType.FriendListPanel]
			.transform.Find("Panel_Center/V_Layout");
		foreach (JsonData temp in respJsonData["data"])
		{
			int userId = (int) temp["userId"];
			string nick = temp["nick"].ToString();
			string avatar = temp["avatar"].ToString();
			User friend = new User();
			friend.Nick = nick;
			friend.Avatar = avatar;
			friend.UserId = userId;
			GameObject friendItemGo = GameObject.Instantiate(_friendItemPrefab, v_Layout_pos, false);
			FriendItem friendItem = friendItemGo.GetComponent<FriendItem>();
			friendItem.User = friend;
			friendItem.SyncShow();
		}
	}
}
